# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
import time
import random
import traceback
import os
import shutil
import re

# ========== 配置部分 ==========
CHROME_PATH = r'C:\Program Files\Google\Chrome\Application\chrome.exe'
EXTENSION_PATH = r'D:\ronin'
EXTENSION_URL = 'chrome-extension://fnjhmkhhmkbjkkabndcnnogagogbneec/src/pages/sidepanel/index.html#/welcome'
GAME_URL = "https://sunflower-land.com/play/"
WALLET_PASSWORD = "7758521love"
MNEMONIC_FILE = r'D:\zjccs.txt'
DEFAULT_USER_DATA_DIR = r'd:\NewChromeUserData'
CHROMEDRIVER_PATH = r'D:\chromedriver-win64\chromedriver.exe'


class RoninAutomation:
    def __init__(self):
        self.driver = None

    def setup_browser(self, user_data_dir):
        """配置浏览器选项"""
        print(f"[初始化] 正在启动浏览器，用户数据目录: {user_data_dir}")

        chrome_options = Options()
        chrome_options.binary_location = CHROME_PATH
        chrome_options.add_argument(f'--user-data-dir={user_data_dir}')
        chrome_options.add_argument(f'--load-extension={EXTENSION_PATH}')
        chrome_options.add_argument('--new-window')

        # 防检测设置
        chrome_options.add_argument("--disable-blink-features=AutomationControlled")
        chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
        chrome_options.add_experimental_option("useAutomationExtension", False)

        # 随机用户代理
        user_agents = [
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36",
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36"
        ]
        chrome_options.add_argument(f"user-agent={random.choice(user_agents)}")

        service = Service(executable_path=CHROMEDRIVER_PATH)
        self.driver = webdriver.Chrome(service=service, options=chrome_options)
        self.driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
        return self.driver

    def random_click(self, element):
        """模拟人类点击"""
        actions = ActionChains(self.driver)
        offset_x = random.randint(-5, 5)
        offset_y = random.randint(-5, 5)
        actions.move_to_element_with_offset(element, offset_x, offset_y).click().perform()
        time.sleep(random.uniform(0.1, 0.3))

    def read_accounts(self):
        """读取助记词文件"""
        accounts = []
        try:
            with open(MNEMONIC_FILE, 'r', encoding='utf-8') as f:
                for line in f:
                    line = line.strip()
                    if line and '|' in line:
                        parts = line.split('|')
                        if len(parts) >= 3:
                            account = {
                                'id': parts[0].strip(),
                                'dir': parts[1].strip(),
                                'mnemonic': ' '.join(parts[2].strip().split())
                            }
                            if len(parts) > 3:
                                account['data_generated'] = parts[3].strip() == '已生成用户数据'
                            else:
                                account['data_generated'] = False
                            accounts.append(account)
            print(f"[读取] 共找到 {len(accounts)} 个账户")
            return accounts
        except Exception as e:
            print(f"[错误] 读取助记词文件失败: {e}")
            return []

    def update_account_record(self, account):
        """更新账户记录，添加已生成用户数据标记"""
        lines = []
        with open(MNEMONIC_FILE, 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                if line and '|' in line:
                    parts = line.split('|')
                    if parts[0].strip() == account['id'] and parts[1].strip() == account['dir']:
                        line = f"{account['id']}|{account['dir']}|{account['mnemonic']}|已生成用户数据"
                lines.append(line)
        with open(MNEMONIC_FILE, 'w', encoding='utf-8') as f:
            for line in lines:
                f.write(line + '\n')

    def unlock_wallet(self):
        """解锁钱包"""
        print("[操作] 正在解锁钱包...")
        try:
            password_input = WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located(
                    (By.CSS_SELECTOR, "input[type='password'][placeholder='Enter your passcode']")
                )
            )

            password_input.clear()
            for char in WALLET_PASSWORD:
                password_input.send_keys(char)
                time.sleep(random.uniform(0.05, 0.15))

            unlock_btn = WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable(
                    (By.CSS_SELECTOR, "button.button-module_button__Z331g.button-module_intent-primary__SAO1x")
                )
            )
            self.random_click(unlock_btn)
            print("[成功] 钱包解锁完成")
            return True
        except Exception as e:
            print(f"[失败] 解锁失败: {e}")
            return False

    def import_wallet(self, account):
        """导入钱包流程"""
        print(f"\n[流程] 开始导入钱包 {account['id']}")

        try:
            # 打开扩展页面
            self.driver.get(EXTENSION_URL)
            time.sleep(2)
            main_window = self.driver.current_window_handle

            # 点击开始按钮
            start_btn = WebDriverWait(self.driver, 15).until(
                EC.element_to_be_clickable(
                    (By.CSS_SELECTOR, 'button.button-module_button__Z331g.button-module_intent-primary__SAO1x')
                )
            )
            self.random_click(start_btn)
            time.sleep(1)

            # 切换到新窗口
            WebDriverWait(self.driver, 15).until(EC.number_of_windows_to_be(2))
            for window in self.driver.window_handles:
                if window != main_window:
                    self.driver.switch_to.window(window)
                    break

            # 选择导入选项
            wallet_options = WebDriverWait(self.driver, 15).until(
                EC.presence_of_all_elements_located((By.CLASS_NAME, '_box_frhkw_1'))
            )
            if len(wallet_options) >= 2:
                self.random_click(wallet_options[1])
                time.sleep(1)

                # 选择助记词导入
                import_options = WebDriverWait(self.driver, 15).until(
                    EC.presence_of_all_elements_located((By.CLASS_NAME, '_box_1xv9l_1'))
                )
                if len(import_options) >= 2:
                    self.random_click(import_options[1])
                    time.sleep(1)

                    # 输入助记词
                    inputs = self.driver.find_elements(By.XPATH, "//input[@type='password']")
                    mnemonic_words = account['mnemonic'].split()

                    for i in range(min(12, len(mnemonic_words), len(inputs))):
                        inputs[i].send_keys(mnemonic_words[i])
                        time.sleep(random.uniform(0.1, 0.3))

                    # 点击导入
                    import_btn = WebDriverWait(self.driver, 15).until(
                        EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), 'Import')]"))
                    )
                    self.random_click(import_btn)
                    time.sleep(2)

                    # 设置密码
                    pwd_inputs = WebDriverWait(self.driver, 15).until(
                        EC.presence_of_all_elements_located((By.XPATH, "//input[@type='password']"))
                    )
                    pwd_inputs[0].send_keys(WALLET_PASSWORD)
                    pwd_inputs[1].send_keys(WALLET_PASSWORD)
                    time.sleep(0.5)

                    # 完成设置
                    continue_btn = WebDriverWait(self.driver, 15).until(
                        EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), 'Continue')]"))
                    )
                    self.random_click(continue_btn)
                    time.sleep(3)

                    finish_btn = WebDriverWait(self.driver, 15).until(
                        EC.element_to_be_clickable((By.CSS_SELECTOR, 'button._finishButton_e8hvq_33'))
                    )
                    finish_btn.click()
                    time.sleep(3)

                    # 返回主窗口
                    WebDriverWait(self.driver, 15).until(lambda d: len(d.window_handles) == 1)
                    self.driver.switch_to.window(main_window)
                    print("[成功] 钱包导入完成")
                    self.update_account_record(account)
                    return True
        except Exception as e:
            print(f"[错误] 导入失败: {e}")
            traceback.print_exc()
            self.driver.save_screenshot(f'error_import_{account["id"]}.png')
            return False

    def direct_login(self, user_data_dir):
        """直接登录游戏"""
        print("[流程] 执行直接登录...")
        try:
            self.setup_browser(user_data_dir)
            self.driver.get(GAME_URL)

            if "chrome-extension://" in self.driver.current_url:
                if not self.unlock_wallet():
                    print("[警告] 自动解锁失败，请手动解锁")

            print("[成功] 已进入游戏")
            return True
        except Exception as e:
            print(f"[错误] 直接登录失败: {e}")
            return False

    def cleanup(self):
        """清理资源"""
        if self.driver:
            self.driver.quit()


def run_ronin_automation():
    print("=== Ronin钱包自动化程序 ===")
    automation = RoninAutomation()

    try:
        accounts = automation.read_accounts()
        if not accounts:
            input("[错误] 没有有效账户，按回车退出...")
            return None

        for account in accounts:
            user_data_dir = os.path.join(DEFAULT_USER_DATA_DIR, account['dir'])
            print(f"\n=== 处理账户 {account['id']} ===")

            if os.path.exists(user_data_dir) and account['data_generated']:
                print("[验证] 文件夹存在且已生成用户数据，直接登录")
                if automation.direct_login(user_data_dir):
                    return automation.driver
            else:
                if os.path.exists(user_data_dir):
                    try:
                        shutil.rmtree(user_data_dir)
                        print("[清理] 旧数据已删除")
                    except Exception as e:
                        print(f"[错误] 删除失败: {e}")
                        continue

                # 新建目录并导入
                os.makedirs(user_data_dir, exist_ok=True)
                automation.setup_browser(user_data_dir)

                if automation.import_wallet(account):
                    if "sunflower-land.com" not in automation.driver.current_url:
                        main_window = automation.driver.current_window_handle
                        automation.driver.execute_script(f"window.open('{GAME_URL}', '_blank');")
                        WebDriverWait(automation.driver, 15).until(lambda d: len(d.window_handles) > 1)
                        for window in automation.driver.window_handles:
                            if window != main_window:
                                automation.driver.switch_to.window(window)
                                break
                    return automation.driver

    except Exception as e:
        print(f"[严重错误] 程序异常: {e}")
        traceback.print_exc()
    finally:
        if not automation.driver:
            automation.cleanup()
    return None


def main():
    print("=== Ronin钱包自动化程序 ===")
    automation = RoninAutomation()

    try:
        accounts = automation.read_accounts()
        if not accounts:
            input("[错误] 没有有效账户，按回车退出...")
            return

        for account in accounts:
            user_data_dir = os.path.join(DEFAULT_USER_DATA_DIR, account['dir'])
            print(f"\n=== 处理账户 {account['id']} ===")

            if os.path.exists(user_data_dir) and account['data_generated']:
                print("[验证] 文件夹存在且已生成用户数据，直接登录")
                if automation.direct_login(user_data_dir):
                    input("按回车退出...")
                    return
            else:
                if os.path.exists(user_data_dir):
                    try:
                        shutil.rmtree(user_data_dir)
                        print("[清理] 旧数据已删除")
                    except Exception as e:
                        print(f"[错误] 删除失败: {e}")
                        continue

                # 新建目录并导入
                os.makedirs(user_data_dir, exist_ok=True)
                automation.setup_browser(user_data_dir)

                if automation.import_wallet(account):
                    if "sunflower-land.com" not in automation.driver.current_url:
                        main_window = automation.driver.current_window_handle
                        automation.driver.execute_script(f"window.open('{GAME_URL}', '_blank');")
                        WebDriverWait(automation.driver, 15).until(lambda d: len(d.window_handles) > 1)
                        for window in automation.driver.window_handles:
                            if window != main_window:
                                automation.driver.switch_to.window(window)
                                break
                    input("按回车退出...")
                    return

    except Exception as e:
        print(f"[严重错误] 程序异常: {e}")
        traceback.print_exc()
    finally:
        automation.cleanup()


if __name__ == "__main__":
    main()